import { List } from "immutable";
import Value from "../model/value";

const reader = new FileReader();
export default function ImportPlugin() {
  return {
    commands: {
      import: editor => {
        const onchange = ({ target }) => {
          const [file] = target.files;
          reader.readAsText(file);
          reader.onload = e => {
            editor.updateValue(Value.create(JSON.parse(e.target.result)), {
              redoStack: List(),
              undoStack: List(),
            });
          };
        };
        const element = document.createElement("input");
        element.setAttribute("type", "file");
        element.setAttribute("accept", "application/json");
        element.onchange = onchange;
        element.style.display = "none";
        document.body.appendChild(element);
        element.click();
      },
    },
  };
}
